package com.wlf.server.common.service;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.wlf.server.common.entity.*;
import com.wlf.server.web.dto.*;
import com.wlf.server.web.util.AjaxBean;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wlf.server.common.mapper.SysDeptMapper;

@Service
public class SysDeptService extends ServiceImpl<SysDeptMapper, SysDept> {

    @Resource
    MappingDTO mappingDTO;

    /**
     * 主数据
     */
    public AjaxBean list(DeptDTO deptDTO) {
        LambdaQueryWrapper<SysDept> wrapper = new LambdaQueryWrapper<>();
        List<SysDept> list = this.list(wrapper);
        TreeNodeConfig tConfig = new TreeNodeConfig();
        tConfig.setIdKey("id");
        tConfig.setChildrenKey("children");
        tConfig.setNameKey("label");

        return AjaxBean.getOkData(getTree(list, tConfig));
    }

    public AjaxBean saveOrUpdate(DeptDTO deptDTO) {
        return AjaxBean.getByBool(Db.saveOrUpdate(mappingDTO.to(deptDTO)));
    }

    public AjaxBean get(String id) {
        return AjaxBean.getOkData(this.getById(id));
    }

    public AjaxBean del(String id) {
        ArrayList<String> deptIds = new ArrayList<>();
        getDeptIds(id, deptIds);
        // 这里需要做递归删除
        return AjaxBean.getByBool(Db.removeByIds(deptIds,this.entityClass));
    }

    public void getDeptIds(String id, List<String> ids) {
        ids.add(id);
        // 此处换成JDBC会更好
        List<SysDept> list = this.lambdaQuery().eq(SysDept::getPid, id).list();
        if (ObjectUtil.isNotEmpty(list)) {
            for (SysDept dept : list) {
                getDeptIds(dept.getId(), ids);
            }
        }
    }

    public AjaxBean parentList() {
        List<SysDept> deptList = this.list();
        SysDept organ = new SysDept();
        organ.setPid("0");
        organ.setId("0");
        organ.setName("根部门");
        deptList.add(organ);
        TreeNodeConfig tConfig = new TreeNodeConfig();
        tConfig.setWeightKey("sort");
        tConfig.setIdKey("value");
        tConfig.setChildrenKey("children");
        tConfig.setNameKey("label");
        return AjaxBean.getOkData(Dict.create()
                .set("pidOptions", this.getTree(deptList, tConfig))
        );
    }

    /**
     * 根据机构ID获取用户ID
     */
    public List<String> getUserIdsByDeptIds(List<String> deptIds) {
        List<DeptUser> organUsers = Db.lambdaQuery(DeptUser.class)
                .in(DeptUser::getDeptId, deptIds).list();
        return organUsers
                .stream().map(DeptUser::getUserId).collect(Collectors.toList());
    }

    public List<DeptDTO> getDeptByUserId(String id) {
        List<DeptUser> list = Db.lambdaQuery(DeptUser.class).eq(DeptUser::getUserId, id).list();
        List<String> deptIds = list.stream().map(DeptUser::getDeptId).collect(Collectors.toList());
        List<SysDept> sysOrgans = this.listByIds(deptIds);


        return mappingDTO.toDeptDTO(sysOrgans);

    }

    /**
     * 获取树形数据
     */
    public List<Tree<String>> getTree(List<SysDept> list, TreeNodeConfig tConfig) {
        //转换器
        return TreeUtil.build(list, "0", tConfig,
                (l, tree) -> {
                    tree.setId(l.getId());
                    tree.setParentId(l.getPid());
                    tree.setWeight(l.getSort());
                    tree.setName(l.getName());
                    tree.putExtra("status", l.getStatus());
                });
    }

}
